package com.demo.springcode;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class springtest {
@Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);
        
        String sql1="insert into student(id,stuname)values(?,?)";
        String sql2="delete from student where id=?";
        String sql3="update student set stuname=? where id=?";
        //增加
        int c1= jdbcTemplate.update(sql1,4,"rose");
        //删除
        jdbcTemplate.update(sql2,4);

        //修改
        jdbcTemplate.update(sql3,"jerry",1);
        
        //批量增加，一次增加多条数据
        List<Object[]> batchArgs = new ArrayList<>();
        batchArgs.add(new Object[]{5, "小明"});
        batchArgs.add(new Object[]{6, "小红"});
        batchArgs.add(new Object[]{7, "小刚"});
        
        int[] updateCounts = jdbcTemplate.batchUpdate(sql1, batchArgs);
        System.out.println("批量插入成功，影响行数：" + updateCounts.length);
        
        // 批量修改
        List<Object[]> updateArgs = new ArrayList<>();
        updateArgs.add(new Object[]{"小明修改", 5});
        updateArgs.add(new Object[]{"小红修改", 6});
        updateArgs.add(new Object[]{"小刚修改", 7});
        
        int[] modifyCounts = jdbcTemplate.batchUpdate(sql3, updateArgs);
        System.out.println("批量修改成功，影响行数：" + modifyCounts.length);
        
        // 批量删除
        List<Object[]> deleteArgs = new ArrayList<>();
        deleteArgs.add(new Object[]{5});
        deleteArgs.add(new Object[]{6});
        deleteArgs.add(new Object[]{7});
        
        int[] deleteCounts = jdbcTemplate.batchUpdate(sql2, deleteArgs);
        System.out.println("批量删除成功，影响行数：" + deleteCounts.length);
    }
}
